package com.yjyw.tiexie.common;


import android.content.Context;
import android.os.Bundle;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;


import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.yjyw.tiexie.common.net.NetCallBack;
import com.yjyw.tiexie.util.ToastUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;

import butterknife.ButterKnife;
import butterknife.Unbinder;

public abstract class BaseFragment extends Fragment implements BaseView {
    /**
     * 标记已加载完成，保证懒加载只能加载一次
     */
    private boolean hasLoaded = false;
    /**
     * 标记Fragment是否已经onCreate
     */
    private boolean isCreated = false;
    /**
     * 界面对于用户是否可见
     */
    private boolean isVisibleToUser = false;
    private View view;
    BaseActivity activity;
    Unbinder unbinder;

    protected InputMethodManager inputMethodManager;

    @Nullable
    @Override
    public View getView() {
        return view;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        activity = (BaseActivity) getActivity();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    }

    protected void hideSoftKeyboard() {
        if (getActivity().getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getActivity().getCurrentFocus() != null)
                inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        //注：关键步骤
        isCreated = true;
        view = inflater.inflate(getFragmentView(), container, false);
        unbinder = ButterKnife.bind(this, view);
        lazyLoad(this.view, savedInstanceState);
        /**初始化的时候去加载数据**/
        return view;
    }


    /**
     * 监听界面是否展示给用户，实现懒加载
     * 这个方法也是网上的一些方法用的最多的一个，我的思路也是这个，不过把整体思路完善了一下
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        this.isVisibleToUser = isVisibleToUser;//注：关键步骤
        super.setUserVisibleHint(isVisibleToUser);
        lazyLoad(view, null);
    }

    @Override
    public void showMessage(String msg) {
        ToastUtil.show(msg);
    }


    /**
     * 懒加载方法，获取数据什么的放到这边来使用，在切换到这个界面时才进行网络请求
     */
    private void lazyLoad(View view, Bundle savedInstanceState) {

        //如果该界面不对用户显示、已经加载、fragment还没有创建，
        //三种情况任意一种，不获取数据
        if (!isVisibleToUser || hasLoaded || !isCreated) {
            return;
        }
        lazyInit(view, savedInstanceState);
        //注：关键步骤，确保数据只加载一次
        hasLoaded = true;
    }

    /**
     * 子类必须实现的方法，这个方法里面的操作都是需要懒加载的
     */
    public abstract void lazyInit(View view, Bundle savedInstanceState);

    @Override
    public void onDestroyView() {
        super.onDestroyView();
//        RefWatcher refWatcher = MyApplication.getRefWatcher(activity);
//        refWatcher.watch(this);
        isCreated = false;
        hasLoaded = false;
        unbinder.unbind();
    }

    /**
     * 重写后 将加载fragment
     *
     * @return
     */
    protected abstract int getFragmentView();

    public static String BaseFile(File file) {
        FileInputStream inputFile = null;
        try {
            inputFile = new FileInputStream(file);
            byte[] buffer = new byte[(int) file.length()];
            inputFile.read(buffer);
            inputFile.close();
            return Base64.encodeToString(buffer, Base64.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }


    /**
     * 网络访问
     *
     * @param callBack 请求回调
     */
    protected void post(HashMap map, String url, int code, NetCallBack callBack) {
        if (activity != null) {
            activity.post(map, url, code, callBack);
        }
    }

    /**
     * 网络访问
     *
     * @param callBack 请求回调
     */
    protected void postJson(HashMap map, String url, int code, NetCallBack callBack) {
        if (activity != null) {
            activity.postJson(map, url, code, callBack);
        }
    }

    /**
     * 网络访问
     *
     * @param callBack 请求回调
     */
    protected void postFile(HashMap map, String url, int code, File file, NetCallBack callBack) {
        if (activity != null) {
            activity.postFile(map, url, code, file, callBack);
        }
    }

    /**
     * 网络访问
     *
     * @param callBack 请求回调
     */
    protected void get(HashMap map, String url, int code, NetCallBack callBack) {
        if (activity != null) {
            activity.get(map, url, code, callBack);
        }
    }

    protected void showProgress(String message) {
        activity.showProgress(message);
    }

    protected void hideProgress() {
        activity.hideProgress();
    }


}